package com.fwh.web.utils.shiro;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 自定义shiro配置加载
 * --由于加上configuration注解和shiroFilter才能实现拦截自定义.
 *
 * @Author: fwh
 * @date 2019/4/4&& 9:04
 */
@Configuration
public class ShiroConfigUtil {
    /**
     * 配置shiroFilterFactoryBean
     */
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter() {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        // 没有登陆的用户只能访问登陆页面
//        shiroFilter.setLoginUrl("/login");
        // 试着securityManager
        shiroFilter.setSecurityManager(securityManager());
        // 权限控制 map.
//        Map<String, String> filterMap = new LinkedHashMap<>();
//        filterMap.put("/qq/*","anon");
//        shiroFilter.setFilterChainDefinitionMap(filterMap);

        return shiroFilter;
    }
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置realm.
        securityManager.setRealm(shiroRealm());
        // 自定义缓存实现
//        securityManager.setCacheManager(cacheManager());
        // 自定义session管理, 使用redis
//        securityManager.setSessionManager(sessionManager());
        return  securityManager;
    }

    /**
     * Session Manager
     * 使用的是shiro-redis开源插件
     */
    @Bean
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
//        sessionManager.setSessionDAO(redisSessionDAO());
        return sessionManager;
    }
    /**
     * RedisSessionDAO shiro sessionDao层的实现 通过redis
     * 使用的是shiro-redis开源插件
     */
  /*  @Bean
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        return redisSessionDAO;
    }*/
    /**
     * 身份认证realm; (这个需要自己写，账号密码校验；权限等)
     */
    @Bean
    public ShiroRealmUtil shiroRealm() {
        ShiroRealmUtil realm = new ShiroRealmUtil();
        //密码加密处理，与加密密码进行匹配
//        realm.setCredentialsMatcher(shiroCredentialMatcher());
        return realm;
    }
    /**
     * 自定义密码处理器
     */
    @Bean
    public ShiroCredentialMatcher shiroCredentialMatcher() {
        return new ShiroCredentialMatcher();
    }
}
